<template>
    <v-layout type="main">
        <div class="detail-layout">
            <el-steps :active="active" simple class="my-steps">
                <el-step title="基本信息" icon="el-icon-edit"></el-step>
                <el-step title="上传文件" icon="el-icon-upload"></el-step>
                <el-step title="构建镜像" icon="el-icon-upload"></el-step>
                <el-step title="完成" icon="el-icon-picture"></el-step>
            </el-steps>
            <el-form ref="form" :model="formData" :rules="submitRules" label-width="120px" class="alick-add-form">
                <div v-if="active == 1">
                    <el-form-item label="范围" prop="type">
                        <el-radio-group v-model="formData.visibility">
                            <el-radio :label='0'>我的</el-radio>
                            <el-radio :label='1'>共享的</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="名称" prop="name">
                        <el-input type="text" v-model="formData.name" />
                    </el-form-item>
                    <el-form-item label="描述" prop="desc">
                        <el-input type="textarea" :rows="6" v-model="formData.desc" />
                    </el-form-item>
                    <el-form-item label="类型" prop="type">
                        <el-radio-group v-model="formData.type" @change="changeEngine()">
                            <el-radio :label="1">训练</el-radio>
                            <el-radio :label="2">推理</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="启动命令行" prop="command" v-if="formData.type == 2">
                        <el-input type="textarea" v-model="formData.command" />
                    </el-form-item>
                    <el-form-item label="端口" prop="port" v-if="formData.type == 2">
                        <el-input type="number" v-model="formData.port" />
                    </el-form-item>

                </div>
                <div v-if="active == 2">
                    <el-form-item label=" " prop=" ">
                      <input type="radio" id="docker" value="docker" v-model="dockerortar"> dockerfile
                      <input type="radio" id="tar" value="tar" v-model="dockerortar" class="radiostyle"> *.tar
                        <wrapUploader @info="succeedOver"  type="build-image" :taskId="path" :biz_id="bizId" />
                    </el-form-item>
                </div>
                <div v-if="active == 3">
                    <el-form-item v-if="formData.type == 1" label="框架" prop="name">
                        <el-radio-group v-model="formData.engine" size="small" @change="changeEngine()">
                            <el-radio-button label='2'>Pytorch</el-radio-button>
                            <el-radio-button label='1'>TensorFlow</el-radio-button>
                            <el-radio-button label='3'>其他</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="基础环境" prop="name">
                        <div class="select">
                            <el-select v-model="fromImage" value-key="id" @change="changFromImage"
                                class="full-extent-select">
                                <el-option v-for="item in imageOptions" :value="item" :label="item.name" :key="item.id">
                                </el-option>
                            </el-select>
                        </div>
                    </el-form-item>
                    <el-form-item label="Dockfile" prop="name">
                        <code-editor :style="{ height: '260px' }" ref="jsonEditor" mode="dockerfile"
                            v-model="dockerFile" />
                        <!-- <el-input type="textarea" v-model="dockerFile" :rows="12" :v-model="formData.dockerFile" /> -->
                    </el-form-item>
                </div>
                <div v-show="active == 4">
                    <p class="succeed-hit" v-if="$route.query.id">修改成功</p>
                    <p class="succeed-hit" v-else>构建成功</p>
                    <div class="succeed-btn">
                        <a href="javascript:;" @click="toDetail">立即前往</a>
                    </div>
                </div>
                <el-form-item label=" ">
                    <el-button class="none-type" @click="addImage1" type="primary" v-if="active == 1">下一步</el-button>
                    <el-button class="none-type" @click="upTo1" v-if="active == 2">上一步</el-button>
                    <el-button class="none-type" @click="goBuildImageTar" type="primary" v-if="active == 2 && dockerortar == 'tar'" >构建</el-button>
                    <el-button class="none-type" @click="next" type="primary" v-if="active == 2 && dockerortar == 'docker'">下一步</el-button>
                    <el-button class="none-type" @click="upTo2" v-if="active == 3">上一步</el-button>
                    <el-button class="none-type" @click="goBuildImage" type="primary" v-if="active == 3">构建</el-button>
                </el-form-item>

            </el-form>
        </div>
    </v-layout>
</template>

<script>
import { labelDicts } from '@/utils/maps'
import {addImage, putImage, getAllImages, buildImage, buildImageTar} from '@/api/images'
import { uploadFile } from "@/api/file"
import { Base64 } from "js-base64";
import CodeEditor from "@/components/module/CodeEditor";
import messesDialog from "@/utils/messesDialog";
export default {
    data() {
        return {
            active: 1,
            formData: { fileSource: '1', visibility: 0, type: 1, engine: 2 },
            submitRules: {
                name: [
                    { required: true, message: "该项为必填项" },
                    { required: true, min: 1, max: 40, message: "长度在1到40个字符" },
                ],
                desc: [
                    { required: true, message: "该项为必填项" },
                    { required: true, min: 1, max: 200, message: "长度在1到200个字符" },
                ],
                command: [
                    { required: true, message: "该项为必填项" },
                    { required: true, min: 1, max: 1000, message: "长度在1到1000个字符" },
                ],
                port: [
                    { required: true, message: "该项为必填项" },
                    { required: true, min: 1, max: 65535, message: "端口范围为1-65535" },
                ],
            },
            labelDicts,
            dockerFile: '',
            imageOptions: [],
            image: {},
            fromImage: null,
            path: this.$route.query.id,
            bizId: this.$route.query.id,
            dockerortar: 'docker',
            isUploadStatus: false,
        };
    },
    components: {
        CodeEditor
    },
    async created() {

    },
    mounted() {
        this.changeEngine()
    },
    destroyed() { },
    methods: {

        /**
          * 添加镜像
        */
        addImage1() {
            this.$refs.form.validate(async (valid) => {
                if (valid) {
                    let res = await addImage(this.formData);
                    this.image = res.data
                    this.bizId = res.data.id
                    if (res && res.data) {
                        this.active = 2;
                    }
                }
            })

        },
        changFromImage() {
            if (this.fromImage) {
                this.formData.base_image_id = this.fromImage.id
                this.dockerFile = 'FROM  ' + this.fromImage.url
            }

        },

        async startBuild() {
            await buildImage({ id: this.bizId })
        },
      async startBuildTar() {
        await buildImageTar({ id: this.bizId })
      },
        /**
         * 下一步
         */
        next() {
            this.active = 3
        },
        async changeEngine() {
            if (this.formData.type == 1) {
                let res = await getAllImages({ visibility: '2', engine: this.formData.engine, type: this.formData.type })
                this.imageOptions = res.data
            }
            else {
                let res = await getAllImages({ visibility: '2', type: this.formData.type })
                this.imageOptions = res.data
            }
        },
        upTo1() {
            this.active = 1
        },
        upTo2() {
            this.active = 2
        },
        /**
         * 构建镜像
         */
        dataURLtoFile(dataurl, filename) {
            //将base64转换为文件
            var arr = dataurl.split(","),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], filename, { type: mime });
        },
        async writeFile() {
            let data = new FormData()
            let filesFile = this.dataURLtoFile(
                `data:text/markdown;base64,${Base64.encode(this.dockerFile)}`,
                'Dockerfile'
            )
            console.log(this.dockerFile)
            let myInfo = await this.$myInfo(this)
            data.append("chunkNumber", 1)
            data.append("totalChunks", 1)
            data.append("repeType", '')
            data.append("filename", filesFile.name)
            data.append("relativePath", '/Dockerfile')
            data.append("userId", myInfo.id)
            data.append("type", 'build-image')
            data.append("bizId", this.bizId)
            data.append("file", new Blob([filesFile]), filesFile.name)

            return await uploadFile(data)
        },
        async goBuildImage() {
            await this.commit();
            await this.startBuild()
            this.toDetail()

            this.active = 4;
        },
      async goBuildImageTar() {
          if(this.dockerortar=="tar"){
            this.formData.build_type="2"//判断是否为.tar
          }
          if(this.isUploadStatus){
            await this.commitTar();
           //await this.delDocker();
            await this.startBuildTar()
            this.toDetail()
            this.active = 4;
          }else{
            await messesDialog({
              message:  `文件未完成上传`,
            })
          }
      },
        async commit() {
            await this.writeFile()
            let res = await putImage({ ...this.image, ...this.formData })
            console.log(res)
        },
      async commitTar() {
       // await this.writeFile()
        let res = await putImage({ ...this.image, ...this.formData })
        console.log(res)
      },
        toDetail() {
            let query = {
                id: this.image.id
            }
            if (this.$route.query.id) {
                query = {
                    id: this.$route.query.id
                }
            }
            this.$router.push({
                path: '/images/code',
                query
            })
        },

        succeedOver(data) {
           this.isUploadStatus=true,
            console.log(data)
        },
    },
};
</script>
<style lang="less" scoped>
.el-form {
    margin-top: 20px;
}

.succeed-hit {
    text-align: center;
    line-height: 120px;
    font-size: 28px;
    font-weight: bold;
    padding-top: 80px;
}

.succeed-btn {
    width: 120px;
    margin: 40px auto 0;

    a {
        display: block;
        text-align: center;
        line-height: 40px;
        border-radius: 4px;
        background: #409EFF;
        color: #FFF;
    }
}

.radiostyle {
  margin-left: 20px;
}
</style>
